package com.extsci.webmail.web.service;

import com.extsci.webmail.common.util.MyFileUtils;
import com.extsci.webmail.common.util.TimeUtils;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * 定时服务
 * @author ccoke
 */
@Service
@Log4j
public class ScheduledService {
    @Value("${webmail.file.path}")
    private String filePath;

    /**
     * temp文件夹清理间隔时间（小时）
     */
    @Value("${webmail.file.clean.interval-time.temp}")
    private Integer tempIntervalTime;

    /**
     * resource文件夹清理间隔时间（小时）
     */
    @Value("${webmail.file.clean.interval-time.resource}")
    private Integer resourceIntervalTime;

    /**
     * 每天中午12点进行清理文件
     */
    @Scheduled(cron="0 0 12 ? * *")
    public void cleanFolder() {
        // 清理Resouce
        File resource = new File(MyFileUtils.contactUri(filePath, MyFileUtils.FILE_SEPARATOR, MyFileUtils.RESOURCE, MyFileUtils.FILE_SEPARATOR));
        cleanDir(resource, TimeUtils.getTimeBeforeCurrent(resourceIntervalTime));

        // 清理Temp
        File temp = new File(MyFileUtils.contactUri(filePath, MyFileUtils.FILE_SEPARATOR, MyFileUtils.TEMP, MyFileUtils.FILE_SEPARATOR));
        cleanDir(temp, TimeUtils.getTimeBeforeCurrent(tempIntervalTime));
    }

    /**
     * 递归清理文件
     */
    private void cleanDir(File file, long seconds){
        if (!file.isDirectory()){
            if (file.lastModified() < seconds){
                log.info("已清理:" + file.getAbsolutePath() + "创建时间:" + file.lastModified());
                file.delete();
            }
        }else {
            File[] files = file.listFiles();
            if (files.length > 0){
                for(int i=0; i<files.length; i++) {
                    cleanDir(files[i], seconds);
                }
            }
            files = file.listFiles();
            if ( files.length == 0){
                log.info("已清理:" + file.getAbsolutePath() + "创建时间:" + file.lastModified());
                file.delete();
            }
        }
    }
}
